var winston = require('winston')
var winstonRotate = require('winston-daily-rotate-file')

var config = require('./loggerconfig')
var morgan = require('morgan')

// var logPath = './log/'
var logPath = '/opt/logs/node/hrywechat/'

var transportInfo = new (winston.transports.DailyRotateFile)({
  timestamp: function () {
    return new Date().toLocaleString()
  },
  name: 'info-file',
  level: 'info',
  json: false,
  filename: logPath + 'default-%DATE%.log',
  // maxsize: 1,//5MB
  // maxFiles: 5,
  zippedArchive: false
})
var transportError = new (winston.transports.DailyRotateFile)({
  timestamp: function () {
    return new Date().toLocaleString()
  },
  name: 'error-file',
  level: 'error',
  json: false,
  filename: logPath + 'error-%DATE%.log',
  // maxsize: 1,
  // maxFiles: '14d',
  zippedArchive: false
})
var transportDebug = new (winston.transports.DailyRotateFile)({
  timestamp: function () {
    return new Date().toLocaleString()
  },
  name: 'debug-file',
  level: 'debug',
  json: false,
  filename: logPath + 'debug-%DATE%.log',
  // maxsize: 1024,//
  // maxFiles: '14d',
  zippedArchive: false
})
var transportException = new (winston.transports.DailyRotateFile)({
  timestamp: function () {
    return new Date().toLocaleString()
  },
  name: 'exception-file',
  filename: logPath + 'exceptions-%DATE%.log',
  json: false,
  // maxsize: 1024,
  // maxFiles: '14d',
  zippedArchive: false
})

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      timestamp: function () {
        return new Date().toLocaleString()
      },
      colorize: 'all',
      json: false
    }),
    transportInfo,
    transportError,
    transportDebug
  ],
  exceptionHandlers: [
    new (winston.transports.Console)({
      timestamp: function () {
        return new Date().toLocaleString()
      },
      colorize: 'all',
      json: true,
      handleExceptions: true
    }),
    transportException
  ],
  levels: config.levels,
  colors: config.colors,
  exitOnError: false // Not to Exit When Catch Exceptions
  // emitErrs: true
})

// setting morgan template info
morgan.token('id', function (req) {
  return req.id
})
morgan.token('cookies', function (req) {
  // console.log('cookies-------')
  // console.log(req)
  return JSON.stringify(req.cookies)
})
morgan.token('params', function (req) {
  return JSON.stringify(req.body)
})

var stream = {
  write: function (message) {
    logger.data(message.slice(0, -1))
  }
}

export {
  logger,
  morgan,
  stream
}

// module.exports = {
//   logger,
//   morgan,
//   stream
// }
